<?php

namespace app\sys\api;

use app\common\logic\Chat;
use app\common\logic\Department;
use my\wechat\QyErrCode;
use my\wechat\QyWeChat;

class Dpt extends Common
{
    private $_wechat = null;

    private function wechat()
    {
        $c = [
            'appid' => c('wx_appid'),
            'appsecret' => c('wx_appsecret')
        ];

        if ($this->_wechat == null)
            $this->_wechat = new QyWeChat($c);

        return $this->_wechat;
    }

    /**
     * 同步部门列表
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function sync()
    {
        if (!$this->checkAuth())
            return $this->_error;

        //获取微信企业号部门列表
        $ret_wx = $this->wechat()->getDepartment();
        if ($ret_wx === false)
            return $this->error(QyErrCode::getErrText($this->wechat()->errCode));

        //删除本地所有部门
        $ret_del = Department::where(['parentid' => ['egt', 0]])->delete();
        if ($ret_del === false)
            return $this->error('删除本地所有部门失败');

        //批量添加部门
        $wx_dept = $ret_wx['department'];
        $temp = [];
        $offset = 1000;

        foreach ($wx_dept as $k => $val) {
            $temp[$k] = $val;
            $code = $val['order'] + $offset;

            $pid = $val['parentid'];
            while ($pid != 0) {
                $child_key = search_2d_array('id', $pid, $wx_dept);
                $pid = $wx_dept[$child_key]['parentid'];
                $code = ($wx_dept[$child_key]['order'] + $offset) . $code;
            }

            $temp[$k]['code'] = $code;
        }

        $department = new Department();
        $ret = $department->addList($temp);
        if ($ret === false)
            return $this->error('批量添加部门失败：' . $department->getError());

        //同步群聊
        $ret_sync_chat = $this->_sync_chat();
        if ($ret_sync_chat !== true)
            return $this->error('同步群聊失败', 4001, $ret_sync_chat);

        return $this->success('同步成功');
    }

    private function _sync_chat()
    {
        $dept_ids = c('create_chat_department_id');
        if (!is_array($dept_ids)) $dept_ids = [$dept_ids];

        $error = [];
        foreach ($dept_ids as $dept_id) {
            $child = Department::where(['parentid' => $dept_id])->column('id');
            foreach ($child as $val) {
                $ret = $this->_add_chat($val);
                if ($ret === false) $error[] = "部门{$val}创建群聊失败";
            }
        }

        if (!empty($error)) return $error;

        return true;
    }

    private function _add_chat($dept_id)
    {
        $dept = Department::get($dept_id);
        $dept_name = $dept['name'];

        $is_exist = Chat::where(['dpt_id' => $dept_id])->find();
        if ($is_exist) return true;

        //获取部门下属子部门
        $dpts = Department::getChildIds($dept_id);
        $optional = empty($dpts) ? '' : ',' . implode(',', $dpts) . ',';

        //创建本地会话
        $data = [
            'dpt_id' => $dept_id,
            'name' => $dept_name,
            'real_name' => $dept_name,
            'optional' => $optional
        ];

        //添加默认会话成员
        $chat_default_userid = c('chat_default_userid');
        if (empty($chat_default_userid)) return false;

        $data['owner'] = $chat_default_userid[0];
        $data['userlist'] = $chat_default_userid;

        $ret_add = Chat::create($data);
        if ($ret_add === false) return false;

        $id = $ret_add->id;
        $chatid = $id . get_rand(6);

        $ret_update = Chat::update(['chatid' => $chatid], ['id' => $id]);
        if ($ret_update === false) {
            Chat::destroy($id);
            return false;
        }

        //创建企业会话
        $ret = \my\wechat\Chat::add($chatid, $dept_name);
        if ($ret === false) {
            Chat::destroy($id);
            return false;
        }

        return true;
    }

    public function lists()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $uid = getUid();

        //todo:判断权限
//        if (!IS_ROOT) {
//            $auth_group_id = AuthGroupAccess::where(['uid' => $uid])->value('group_id');
//            if (empty($auth_group_id))
//                return $this->success([]);
//            else {
//                //根据权限显示部门
//                $pid = 0;
//                $authgroup_id_department_id = c('authgroup_id_department_id');
//                foreach ($authgroup_id_department_id as $val) {
//                    if ($auth_group_id == $val['id']) {
//                        $pid = $val['name'];
//                        break;
//                    }
//                }
//
//                if (empty($pid)) return $this->success([]);
//            }
//        } else
        $pid = 1;

        $ret = Department::getTreeByPid($pid);
        return $this->success($ret);
    }
}